<template>
  <div>
    <!-- 选择按钮 -->
    <a-input
      :placeholder="placeholder"
      :disabled="disabled"
      :value="selectedLabel"
      :allowClear="true"
      @click="showModal"
      readOnly
      style="width: 100%"
    >
      <a-icon slot="suffix" type="search" />
    </a-input>
    
    <!-- 订单选择模态框 -->
    <a-modal
      :title="title"
      :width="1000"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
    >
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="8" :sm="12">
              <a-form-item label="订单编号">
                <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="客户名称">
                <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="工程名称">
                <a-input placeholder="请输入工程名称" v-model="queryParam.projectName" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      
      <!-- 表格区域 -->
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox' : 'radio'}"
        @change="handleTableChange"
      >
        <!-- 订单状态 -->
        <template slot="statusSlot" slot-scope="text">
          <j-dict-tag :value="text" dictCode="order_status"/>
        </template>
        
        <!-- 金额格式化 -->
        <template slot="moneySlot" slot-scope="text">
          <span v-if="text !== undefined && text !== null">{{ Number(text).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 }) }}</span>
          <span v-else>¥0.00</span>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictTag from '@/components/dict/JDictTag'

export default {
  name: 'JSelectProductOrder',
  mixins: [JeecgListMixin],
  components: {
    JDictTag
  },
  props: {
    placeholder: {
      type: String,
      default: '请选择订单'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Array],
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    orderStatus: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '选择订单'
    }
  },
  data() {
    return {
      visible: false,
      selectedLabel: '',
      selectedRowKeys: [],
      selectedRows: [],
      internalValueChange: false, // 标记是否是内部选择触发的值变化
      url: {
        list: '/oms/productSalesOrder/approvedList'
      },
      queryParam: {
        orderNo: '',
        customerName: '',
        projectName: '',
        orderStatus: this.orderStatus
      },
      columns: [
        {
          title: '订单编号',
          align: "center",
          dataIndex: 'orderNo',
          width: 120
        },
        {
          title: '客户名称',
          align: "center",
          dataIndex: 'customerName',
          width: 120
        },
        {
          title: '工程名称',
          align: "center",
          dataIndex: 'projectName',
          width: 120
        },
        {
          title: '下单日期',
          align: "center",
          dataIndex: 'orderDate',
          width: 100
        },
        {
          title: '交付日期',
          align: "center",
          dataIndex: 'deliveryDate',
          width: 100
        },
        {
          title: '销售额',
          align: "center",
          dataIndex: 'totalAmount',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' }
        },
        {
          title: '订单状态',
          align: "center",
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' }
        }
      ],
      dataSource: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      loading: false
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        // 只有当值变化且不是由内部选择触发时才初始化
        if (val && !this.internalValueChange) {
          this.initSelectedValue(val);
        }
      }
    },
    orderStatus: {
      immediate: true,
      handler(val) {
        if (val) {
          this.queryParam.orderStatus = val
        }
      }
    }
  },
  methods: {
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      const params = this.getQueryParams();
      this.loading = true;
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
            
            // 如果有已选值，需要标记选中状态
            this.updateSelectedRows();
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 初始化已选值
    initSelectedValue(val) {
      if (!val || (Array.isArray(val) && val.length === 0)) {
        this.selectedRowKeys = [];
        this.selectedRows = [];
        this.selectedLabel = '';
        return;
      }
      
      // 检查当前数据源中是否已包含所需数据
      if (this.dataSource && this.dataSource.length > 0) {
        const valArray = Array.isArray(val) ? val : [val];
        const existingRows = this.dataSource.filter(item => valArray.includes(item.id));
        
        // 如果在当前数据源中找到了所有需要的数据，直接使用
        if (existingRows.length === valArray.length) {
          this.selectedRows = existingRows;
          this.selectedRowKeys = existingRows.map(item => item.id);
          
          // 设置显示文本
          if (existingRows.length === 1) {
          //显示 订单编号-客户名称-工程名称
          this.selectedLabel = `${existingRows[0].orderNo}-${existingRows[0].customerName}-${existingRows[0].projectName}`
          } else if (existingRows.length > 1) {
            this.selectedLabel = `已选择 ${existingRows.length} 个订单`;
          }
          return;
        }
      }
      
      // 如果当前数据源中没有所需数据，则调用接口获取
      const params = {
        ids: Array.isArray(val) ? val.join(',') : val
      };
      
      getAction('/oms/productSalesOrder/listByIds', params).then(res => {
        if (res.success && res.result) {
          const records = Array.isArray(res.result) ? res.result : [res.result];
          this.selectedRows = records;
          this.selectedRowKeys = records.map(item => item.id);
          
          // 设置显示文本
          if (records.length === 1) {
            // 修改显示格式为"订单编号-客户名称-工程名称"
            this.selectedLabel = `${records[0].orderNo}-${records[0].customerName}-${records[0].projectName}`;
          } else if (records.length > 1) {
            this.selectedLabel = `已选择 ${records.length} 个订单`;
          }
        }
      });
    },
    
    // 更新选中行的状态
    updateSelectedRows() {
      if (this.selectedRowKeys.length > 0) {
        // 从当前数据源中找到已选择的行
        const selectedRows = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id));
        if (selectedRows.length > 0) {
          this.selectedRows = selectedRows;
        }
      }
    },
    
    // 显示模态框
    showModal() {
      if (this.disabled) return;
      this.visible = true;
      this.loadData(1);
    },
    
    // 确认选择
    handleOk() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请至少选择一条记录!');
        return;
      }
      
      // 设置显示文本
      if (this.selectedRows.length === 1) {
        // 修改显示格式为"订单编号-客户名称-工程名称"
        this.selectedLabel = `${this.selectedRows[0].orderNo}-${this.selectedRows[0].customerName}-${this.selectedRows[0].projectName}`;
      } else if (this.selectedRows.length > 1) {
        this.selectedLabel = `已选择 ${this.selectedRows.length} 个订单`;
      }
      
      // 设置内部值变化标记，避免触发watch重新加载
      this.internalValueChange = true;
      
      // 触发change事件
      const selectedValues = this.multiple ? this.selectedRowKeys : this.selectedRowKeys[0];
      this.$emit('change', selectedValues, this.selectedRows);
      
      // 下一个事件循环中重置标记
      this.$nextTick(() => {
        this.internalValueChange = false;
      });
      
      // 关闭模态框
      this.handleCancel();
    },
    
    // 取消选择
    handleCancel() {
      this.visible = false;
    },
    
    // 选择行变化
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    
    // 查询
    searchQuery() {
      this.loadData(1);
    },
    
    // 重置查询条件
    searchReset() {
      this.queryParam = {
        orderNo: '',
        customerName: '',
        projectName: '',
        orderStatus: this.orderStatus
      };
      this.loadData(1);
    },
    
    // 表格分页变化
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination;
      this.loadData();
    },
    
    // 获取查询参数
    getQueryParams() {
      const param = Object.assign({}, this.queryParam);
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return param;
    }
  }
}
</script>

<style scoped>
.table-page-search-wrapper {
  margin-bottom: 8px;
}
</style> 